import Router from "@koa/router";
import { generateVerificationCode, sendVerificationEmail } from '../utils/emailService.js';
import multer from '@koa/multer';
import fs from 'fs';
import path from 'path';  // 添加 path 模块

const router = new Router();

// 存储验证码的 Map（在实际生产环境中应该使用 Redis）
const verificationCodes = new Map();

// 发送验证码
router.post('/email/send-code', async (ctx) => {
    const { email } = ctx.request.body;
    
    if (!email) {
        ctx.status = 400;
        ctx.body = { success: false, message: '邮箱不能为空' };
        return;
    }

    const code = generateVerificationCode();
    const success = await sendVerificationEmail(email, code);

    if (success) {
        // 存储验证码，5分钟后过期
        verificationCodes.set(email, {
            code,
            expires: Date.now() + 5 * 60 * 1000
        });
        
        ctx.body = { success: true, message: '验证码已发送' };
    } else {
        ctx.status = 500;
        ctx.body = { success: false, message: '验证码发送失败' };
    }
});

// 验证验证码
router.post('/email/verify-code', async (ctx) => {
    const { email, code } = ctx.request.body;

    if (!email || !code) {
        ctx.status = 400;
        ctx.body = { success: false, message: '邮箱和验证码不能为空' };
        return;
    }

    const storedData = verificationCodes.get(email);
    
    if (!storedData) {
        ctx.status = 400;
        ctx.body = { success: false, message: '验证码不存在' };
        return;
    }

    if (Date.now() > storedData.expires) {
        verificationCodes.delete(email);
        ctx.status = 400;
        ctx.body = { success: false, message: '验证码已过期' };
        return;
    }

    if (storedData.code !== code) {
        ctx.status = 400;
        ctx.body = { success: false, message: '验证码错误' };
        return;
    }

    // 验证成功后删除验证码
    verificationCodes.delete(email);
    ctx.body = { success: true, message: '验证成功' };
});

// 确保上传目录存在
const uploadDir = 'uploads';
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置 multer
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 从 file.originalname 中获取 hash
        const hash = decodeURIComponent(file.originalname).split('_')[0].split('.')[0];
        const chunkDir = path.join(uploadDir, hash);
        
        // 确保分片目录存在
        if (!fs.existsSync(chunkDir)) {
            fs.mkdirSync(chunkDir, { recursive: true });
        }
        cb(null, chunkDir);
    },
    filename: function (req, file, cb) {
        // 从文件名中提取信息
        const decodedName = decodeURIComponent(file.originalname);
        const [hash, index] = decodedName.split('_');
        cb(null, index);
    }
});

const upload = multer({ storage: storage });

// 使用预处理中间件
router.post('/upload', upload.single('file'), async (ctx) => {
    try {
        const file = ctx.file;
        
        if (!file) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '没有检测到上传的文件'
            };
            return;
        }

        // 返回文件信息
        ctx.body = {
            success: true,
            message: '文件上传成功',
            data: {
                filename: file.filename,
                originalname: file.originalname,
                mimetype: file.mimetype,
                size: file.size,
                path: file.path
            }
        };
    } catch (error) {
        console.error('文件上传错误:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '文件上传过程中发生错误'
        };
    }
});

// 添加合并文件的路由
router.post('/merge', async (ctx) => {
    try {
        const { filename } = ctx.request.body;
        if (!filename) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '文件名不能为空'
            };
            return;
        }

        // 获取文件名（不含扩展名）作为切片文件夹名
        const fileNameWithoutExt = filename.split('.')[0];
        const chunkDir = path.join('uploads', fileNameWithoutExt);
        const filePath = path.join('uploads', filename);

        // 读取所有切片
        const chunks = fs.readdirSync(chunkDir);
        
        // 按照索引排序
        chunks.sort((a, b) => a - b);

        // 创建写入流
        const writeStream = fs.createWriteStream(filePath);
        
        // 依次写入切片
        for (const chunk of chunks) {
            const chunkPath = path.join(chunkDir, chunk);
            const chunkData = fs.readFileSync(chunkPath);
            writeStream.write(chunkData);
        }
        writeStream.end();

        // 等待写入完成
        await new Promise((resolve, reject) => {
            writeStream.on('finish', resolve);
            writeStream.on('error', reject);
        });

        // 删除切片文件夹
        chunks.forEach(chunk => {
            fs.unlinkSync(path.join(chunkDir, chunk));
        });
        fs.rmdirSync(chunkDir);

        ctx.body = {
            success: true,
            message: '文件合并成功',
            data: {
                filename: filename,
                path: filePath
            }
        };
    } catch (error) {
        console.error('文件合并错误:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '文件合并过程中发生错误',
            error: error.message
        };
    }
});

export default router;